package com.htfyun.eink.pw.draw.pen.epd.charcoal;

public class TextureBmpHelper {
    private static final float RADIAN = 5.3931f;

    private static final float VAL_COS = (float) Math.cos(RADIAN);
    private static final float VAL_SIN = (float) Math.sin(RADIAN);

    public static void init(BitmapData bitmapData) {

        for (int i = 0; i < bitmapData.width; i++) {
            for (int j = 0; j < bitmapData.height; j++) {
                bitmapData.data[i][j] = 0xFF000000;
            }
        }

        final float halfRow = bitmapData.width * 0.5f;
        final float halfColumn = bitmapData.height * 0.5f;

        for (int row = 0; row < bitmapData.width; row++) {

            float rowDiff = row - halfRow;

            for (int column = 0; column < bitmapData.height; column++) {

                float columnDiff = column - halfColumn;

                float cos = columnDiff * VAL_COS - rowDiff * VAL_SIN;
                float sin = columnDiff * VAL_SIN + rowDiff * VAL_COS;

                int cp = compute(bitmapData.width, cos, sin);

                int data = bitmapData.data[row][column];
                int result = MathUtils.uint8_multiple((data >> 0x18), (~cp));

                bitmapData.data[row][column] = data & 0xFFFFFF | (result << 0x18);

            }
        }
    }

    private static int compute(int width, float cos, float sin) {
        int result = 0xFF;

        if (width <= 0) {
            return result;
        }

        float MUL_CONSTANT = 1.25f;
        float ERF_CONSTANT = -3.4615f;

        double v0 = 0.5D;//0.5
        double v1 = 2D;//2
        double v2 = 17677.66922712326D;
        double v3 = 255D;

        double d0 = width * 3380.5D;
        double d1 = MathUtils.erf(ERF_CONSTANT);

        double t0 = v0 * d0;
        double t1 = v1 * d1;

        float ratio0 = (float) (v2 / t0);
        float ratio1 = (float) (v3 / t1);

        float x = cos;
        float y = Math.abs(sin) * MUL_CONSTANT;
        float hypot = (float) Math.hypot(x, y);
        if ((width * 0.5F) >= hypot) {
            float s11 = hypot * ratio0;
            float erf1 = (float) MathUtils.erf(s11 + ERF_CONSTANT);
            float erf2 = (float) MathUtils.erf(s11 - ERF_CONSTANT);
            result = 0xFF - (int) (ratio1 * (erf1 - erf2));
        }

        return result;

    }
}
